package users

import (
	exc "hsy/app/exceptions"
	"hsy/app/models"
	request "hsy/app/requests"
	"hsy/config"
	"hsy/util"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)

// Create 新增用户
func Create(c *gin.Context) {
	var r request.UserCreateRequest
	if err := c.Bind(&r); err != nil {
		exc.SendResponse(c, exc.ErrBind, nil)
		return
	}
	password, _ := util.EncryptPassword(r.Password)

	u := models.UserModel{
		Name:     r.Name,
		Sex:      r.Sex,
		Username: r.Username,
		Password: password,
	}

	// Validte
	if msg, err := r.ValidateCreate(); err != nil {
		exc.SendValidResponse(c, msg)
		return
	}

	if err := u.Create(); err != nil {
		exc.SendResponse(c, exc.ErrDatabase, nil)
		return
	}

	exc.SendResponse(c, exc.OK, nil)
}

// Update 用户更新信息
func Update(c *gin.Context) {
	var r request.UserUpdateRequest
	var u models.UserModel
	if err := c.Bind(&r); err != nil {
		exc.SendResponse(c, exc.ErrBind, nil)
	}

	// Validte
	if msg, err := r.ValidateUpdate(); err != nil {
		exc.SendValidResponse(c, msg)
		return
	}

	// password 是否更新
	if r.Password == "" {
		u = models.UserModel{
			Name:     r.Name,
			Sex:      r.Sex,
			Username: r.Username,
		}
	} else {
		password, _ := util.EncryptPassword(r.Password)
		u = models.UserModel{
			Name:     r.Name,
			Sex:      r.Sex,
			Username: r.Username,
			Password: password,
		}
	}

	if ok := u.CheckExceptSelf(r.Username, r.ID); ok {
		exc.SendResponse(c, exc.ErrAlExist, nil)
		return
	}

	if err := u.Update(r.ID); err != nil {
		exc.SendResponse(c, exc.ErrDatabase, nil)
		return
	}

	exc.SendResponse(c, exc.OK, nil)
}

// Delete 删除用户
func Delete(c *gin.Context) {
	id := c.Param("id")
	intID, _ := strconv.Atoi(id[1:len(id)])
	u := models.UserModel{}
	if err := u.Delete(intID); err != nil {
		exc.SendResponse(c, exc.ErrDatabase, nil)
	}
	exc.SendResponse(c, exc.OK, nil)
}

// List 列表
func List(c *gin.Context) {
	var users []models.UserModel
	var total int
	var db *gorm.DB = config.Self
	var columns string = "id, name, sex, username, created_at, updated_at"
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "15"))
	// wheres := map[string]interface{}{"name": c.Query("name"), "pageSize": c.Query("username")}
	if c.Query("name") != "" {
		db = db.Where("name", c.Query("name"))
	}
	if c.Query("username") != "" {
		db = db.Where("username", c.Query("usernmae"))
	}
	db, err := config.QueryList(db, nil, columns, "", page, pageSize)
	if err != nil {
		exc.SendResponse(c, exc.ErrQuery, nil)
		return
	}
	db.Find(&users).Count(&total)
	exc.SendResponse(c, exc.OK, models.ListResponse{Total: total, List: users})
}
